import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
import random
import time
import collections
import requests
import pickle
from urllib.request import Request, urlopen
from urllib.error import URLError
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
import requests
#!pip install line_profiler
%load_ext line_profiler
matplotlib.rcParams["axes.titlesize"] = 16
matplotlib.rcParams["axes.labelsize"] = 13
matplotlib.rcParams["xtick.labelsize"] = 16
matplotlib.rcParams["ytick.labelsize"] = 16
matplotlib.rcParams["axes.grid"] = True
matplotlib.rcParams["xtick.major.size"] = 12
matplotlib.rcParams["ytick.major.size"] = 12
matplotlib.rcParams["xtick.major.width"] = 2
matplotlib.rcParams["ytick.major.width"] = 2
N = 2*10**4
G = nx.barabasi_albert_graph( N , 1) #Creating a nx.Graph object
#degree counting
def deg_dist(G):
degreeSequence = sorted([d for n, d in G.degree()]) #degree list - ascending
degreeCount = collections.Counter(degreeSequence)
deg, cnt = zip( *degreeCount.items() )
return deg, cnt
def plot_deg_dist(deg,cnt):
plt.bar(deg,[x/N for x in cnt], color="tab:orange", label="degree distribution") #It would be more practical to use a histogram, but it is prettier
plt.grid()
deg_grid = np.arange(1,max(deg)+1, dtype = float)
plt.plot( deg_grid ,[2.5 * k**(-3) for k in deg_grid],
color="tab:green",ls="--",label="theoretical distribution: ~$k^{-3}$") #source: Wiki on Barabási-Albert network
plt.title(f"{N} node degree distribution",size=24)
plt.xlabel("k - degree", size=20)
plt.ylabel("$P_k$",size=20)
plt.legend(fontsize=14)
plt.yscale("log")
plt.xlim(0,50)
fig,ax = plt.subplots(figsize=[8,6])
deg, cnt = deg_dist(G)
plot_deg_dist(deg, cnt)
def swap_edge(i,ax):
edgeList = list(G.edges)
edgeCount = len(G.edges)
ax.clear()
#oops_meter = 0
#get a random index pair (row,col) from the adjacency matrix
chosenEdge = random.choice(edgeList)
for j in range(100):
#find non-existing edge: check if a random index pair is not in the edge list
plannedEdge = [random.randint(0,edgeCount),random.randint(0,edgeCount)]
if plannedEdge not in G.edges:
#delete chosen edge, add the planned edge
try:
G.remove_edge(*chosenEdge)
except Exception: #Some unkown error happens sometimes
pass #oops_meter +=1
G.add_edge(*plannedEdge)
break
deg, cnt = deg_dist(G)
plot_deg_dist(deg,cnt)
fig, ax = plt.subplots(figsize=[8,6])
ani = FuncAnimation(fig, swap_edge, interval = 1, fargs = [ax], repeat = False, frames = 500)
#ani.save('task1.gif', writer='ffmpeg')
HTML(ani.to_jshtml())